//
//  HomePageViewController.m
//  ZAKER
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "HomePageViewController.h"


@interface HomePageViewController ()<JCFlipPageViewDataSource,UMSocialUIDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
{
    
    NSNumber *firstNum;
    NSNumber *secondNum;
    
}
@property (nonatomic, strong) JCFlipPageView *flipPage;
@property (nonatomic, retain) NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableArray *middleArr;
@property (nonatomic, retain) HomeModel *detailModel;
@property (nonatomic, retain) NSMutableArray *buttonArray; // 存放顶部按钮的信息
@property (nonatomic, retain) UITableView *homePageTable;
@property (nonatomic, retain) NSMutableArray *talbeViewArray;
@property (nonatomic, retain) UIActivityIndicatorView *activity;
@property (nonatomic, retain) UIView *xiqiView; // 放置稀奇界面的view
@property (nonatomic, retain) UIScrollView *headerScro; // 顶部滚动Scroll, 热点,头条, 稀奇
@property (nonatomic, retain) NSDictionary *buttonDic; // 点击不同按钮dic
@property (nonatomic, retain) MBProgressHUD *mb;
@property (nonatomic, retain) UIScrollView *bigScroll;

@end

@implementation HomePageViewController
-(void)dealloc
{
    [_flipPage release];
    [_middleArr release];
    [_myArray release];
    [_detailModel release];
    [_buttonArray release];
    [_homePageTable release];
    [_activity release];
    [_headerScro release];
    [_buttonDic release];
    [_mb release];
    [_xiqiView release];
    [_talbeViewArray release];
    
    [super dealloc];
    
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.middleArr = [NSMutableArray array];
        self.myArray = [NSMutableArray array];
        self.buttonArray = [NSMutableArray array];
        self.talbeViewArray = [NSMutableArray array];
        
    }
    
    return self;
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor  = RGBACOLOR(240, 51, 51, 1);
    self.navigationItem.title = @"新闻";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 创建顶部横向按钮
    [self createBigScroll];
    [self createHeaderButton];
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _mb = [[MBProgressHUD alloc] initWithView:window];
    [window addSubview:_mb];
    _mb.labelText = @"正在加载";
    [_mb show:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        if (_mb != nil) {
            [_mb removeFromSuperview];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert  show];
            [alert release];
            
        }
    });
    
    
    // 创建tableView
    [self createTableView];
    
}

#pragma mark - 创建头条, 热点, 稀奇的三个button, 放在scrollView上

- (void)createHeaderButton
{
    
    self.headerScro = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, HeaderScrollHeight)] autorelease];
    _headerScro.backgroundColor = [UIColor colorWithRed:244 / 255.0 green:244 / 255.0 blue:244 / 255.0 alpha:1.0f];
    _headerScro.bounces = NO;
    [self.view addSubview:_headerScro];
//    [_headerScro release];
    
    // 从json文件解析出来按钮的信息
    NSString *path = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    [self.buttonArray addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
    
    // 创建不同按钮 (tag 值从50开始)
    CGFloat offX = 30 * myWidth;
    
    for (int i = 0; i < [self.buttonArray count]; i++) {
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(offX , 5, 50 * myWidth, 30 * myHeight)];
        NSDictionary *dic = [self.buttonArray objectAtIndex:i];
        NSString *name = dic[@"name"];
        button.tag = 50 + i;
        [button setTitle:name forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_headerScro addSubview:button];
        offX += 120 * myWidth;
        
        // 默认调用第一个按钮
        if (button.tag == 50) {
            
            [self buttonAction:button];
            
        }
    }
    
    _headerScro.contentSize = CGSizeMake(offX, 0);
    
}


#pragma mark - 加风火轮

- (UIActivityIndicatorView *)activity
{
    if (_activity == nil) {
        
        self.activity = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
        
    }
    
    return _activity;
    
}


- (void)getConnectionWithURL:(NSString *)url dicNum:(NSString *)num
{
    url = [NSString stringWithFormat:@"%@%@-%@.html", url, firstNum, secondNum];
    [MyAFNetworking GetWithURL:url dic:nil data:^(id responsder) {
        NSArray *array = responsder[num];
        for (NSDictionary *dic in array) {
            WangYiModel *model = [[WangYiModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            model.editor = dic[@"editor"];
            
            // 以下条件过滤掉
            if (![model.imgextra count] != 0 || [model.editor count] != 0) {
                [self.talbeViewArray addObject:model];
                [model release];
            }
        }
        [self.homePageTable reloadData];
        [self.homePageTable headerEndRefreshing];
        [self.homePageTable footerEndRefreshing];
        [_mb hide:YES];
        _mb = nil;
    }];
}

- (void)createBigScroll
{
    self.bigScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, HeaderScrollHeight, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:self.bigScroll];
    self.bigScroll.contentSize = CGSizeMake(self.view.frame.size.width * 3, 0);
    self.bigScroll.pagingEnabled = YES;
    self.bigScroll.backgroundColor = [UIColor yellowColor];
}

#pragma mark - 创建头条的tableView

- (UITableView *)homePageTable
{
    
    if (_homePageTable == nil) {
        self.homePageTable = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bigScroll.contentOffset.x, self.view.frame.size.height - 49 - 64 - HeaderScrollHeight  * myHeight) style:UITableViewStylePlain] autorelease];
    }
    
    return _homePageTable;
    
}

#pragma mark - 创建TableView以及他的协议方法, 第一页的tableView, 算上面的照片

- (void)createTableView
{
    [self.bigScroll addSubview:self.homePageTable];
    self.homePageTable.delegate = self;
    self.homePageTable.dataSource = self;
    [self.homePageTable registerClass:[HeaderViewCell class] forCellReuseIdentifier:@"HeaderViewCell"];
    [self.homePageTable registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
    
    // 添加上拉刷新控件
    [self.homePageTable addFooterWithCallback:^{
        
        firstNum = secondNum;
        secondNum = @(secondNum.integerValue + 21);
        
        [self getConnectionWithURL:_buttonDic[@"url"] dicNum:_buttonDic[@"dicNum"]];
        
    }];
    
    // 添加下拉加载控件
    [self.homePageTable addHeaderWithCallback:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.talbeViewArray removeAllObjects];
            firstNum = @0;
            secondNum = @20;
            [self getConnectionWithURL:_buttonDic[@"url"] dicNum:_buttonDic[@"dicNum"]];
            
        });
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row) {
       
        return 300 * myHeight;
      
    }
    else {
        
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        
        return cell.frame.size.height;
        
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [_talbeViewArray count];
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([_talbeViewArray count] != 0) {
    WangYiModel *model = [_talbeViewArray objectAtIndex:indexPath.row];
        
    // 判断数组里的东西去区分用哪种cell
    // 第一种cell就是放顶部大图

    if (0 == indexPath.row) {
        
        HeaderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HeaderViewCell"];
        NSString *imageURL = model.imgsrc;
        
        [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:imageURL]placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
        [cell.coinImage setImage:[UIImage imageNamed:@"1"]];
        [cell.titleLabel setText:model.title];
        
        return cell;
        
    } else {
        
        CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
        
        [cell.newsImageView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"pla.jpg"]];
        [cell.newsLabel setText:model.digest];
        [cell.newsTitleLabel setText:model.title];
        
        return cell;
        
    }
}
    
    return [[UITableViewCell alloc] init];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WangYiModel *model = _talbeViewArray[indexPath.row];

    HomePageWeb *web = [[HomePageWeb alloc] init];
    web.url = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html", model.docid];
    web.deoId = model.docid;
    
    [self.navigationController pushViewController:web animated:YES];
    [web release];

}

#pragma mark - 调用方法
- (void)createLast
{
    
    [self myConnection];
    [self createMyView];
    [self createCJFilpView];
    
}
#pragma mark - 数据解析

-(void)myConnection
{
    
    [MyAFNetworking GetWithURL:ShouYe dic:nil data:^(id responsder) {
        
        NSArray *array = [responsder objectForKey:@"content"];
        for (int i = 0 ; i < [array count]; i++) {
            NSArray *brray = [[array objectAtIndex:i] objectForKey:@"image_urls"];
            NSDictionary *dic  = brray.lastObject;
            [self.middleArr addObject:dic]; // 存图片
            
            HomeModel *model = [[HomeModel alloc] init];
            [model setValuesForKeysWithDictionary:[array objectAtIndex:i]];
            [self.myArray addObject:model]; // self.myArray存字符串
            [model release];
            
        }
        
        [_flipPage reloadData];
        [_mb hide: YES];
        
    }];
}

#pragma mark - 创建稀奇页面头部的照片和label,固定的内容和照片

-(void)createMyView
{
    
    UIImageView *myImage = [[UIImageView alloc]initWithFrame:CGRectMake(20 * myWidth, 20 * myHeight, 100 * myWidth, 100 *myHeight)];
    [myImage setImage:[UIImage imageNamed:@"logo.jpg"]];
    [self.xiqiView addSubview:myImage];
    [myImage release];
    
    NSArray *array = [NSArray arrayWithObjects:@"包括", @"凤凰新闻", @"界面新闻" , @"Filpboard", @"ZAker", nil];
    for (int i = 0; i < 5 ; i++) {
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(260 * myWidth, 10 * myHeight + i * 20 * myHeight, 80 * myWidth, 50 * myHeight)];
        label.text = [array objectAtIndex:i];
        label.numberOfLines = 0;
        [self.xiqiView addSubview:label];
        label.textAlignment = 2;
        label.font = [UIFont systemFontOfSize:15];
        [label release];
        
    }
}


#pragma mark - 创建JCFilpPageView,页面翻动效果, 以及协议方法

-(void)createCJFilpView
{
    
    self.flipPage = [[JCFlipPageView alloc] initWithFrame:CGRectMake(0, 120 * myHeight, self.view.frame.size.width, self.view.frame.size.height - 200 * myHeight)];
    [self.xiqiView addSubview:_flipPage];
    _flipPage.dataSource = self;
    [_flipPage reloadData];
    [_flipPage release];
    
}


- (NSUInteger)numberOfPagesInFlipPageView:(JCFlipPageView *)flipPageView
{
    
    return self.myArray.count  - 2;
    
}
- (JCFlipPage *)flipPageView:(JCFlipPageView *)flipPageView pageAtIndex:(NSUInteger)index
{
    
    static NSString *kPageID = @"numberPageID";
    JCFlipPage *page = [flipPageView dequeueReusablePageWithReuseIdentifier:kPageID];
    
    if (!page) {
        
        page = [[JCFlipPage alloc] initWithFrame:flipPageView.bounds reuseIdentifier:kPageID];
    };
    if ([_middleArr count] != 0) {
        
        static dispatch_once_t once;
        dispatch_once(&once, ^{
            
            [_middleArr removeObjectAtIndex:0];
            [_myArray removeObjectAtIndex:0];
            [_middleArr removeLastObject];
            [_myArray removeLastObject];
        });
        
        page.image_urls.target = self;
        page.image_urls.action = @selector(imageAction:);
        
        NSString *str = [[_middleArr objectAtIndex:index ] objectForKey:@"middle"];
        HomeModel *model = [_myArray objectAtIndex:index ];
        _detailModel = model;
        
        [page.image_urls sd_setImageWithURL:[NSURL URLWithString:str]  placeholderImage:nil];
        [page.publisher_icon_url  sd_setImageWithURL:[NSURL URLWithString:model.publisher_icon_url] placeholderImage:nil];
        page.publisher_name.text = model.publisher_name;
        page.good_count.text =  [NSString stringWithFormat:@"%@", model.good_count];
        page.bad_count.text = [NSString stringWithFormat:@"%@", model.bad_count] ;
        [page.share_count setTitle: [NSString stringWithFormat:@"%@", model.share_count] forState:UIControlStateNormal];
        [page.share_count setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        page.text.text = [NSString stringWithFormat:@"    %@", model.text] ;
        page.zanImage.image = [UIImage imageNamed:@"zan.png"];
        page.caiImage.image = [UIImage imageNamed:@"cai.png"];
        page.shareImage.image = [UIImage imageNamed:@"share.png"];
        
        [page.share_count addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    [self createActivityRoll];
    
    return page;
    
}

#pragma mark - 创建稀奇那一页面的View

- (UIView *)xiqiView
{
    if (_xiqiView == nil) {
        self.xiqiView = [[UIView alloc] initWithFrame:CGRectMake(0, HeaderScrollHeight * myHeight, self.view.frame.size.width, self.view.frame.size.height)];
        [self.view addSubview:_xiqiView];
        [_xiqiView release];
        
    }
    
    return _xiqiView;
}


#pragma mark - 创建小圆圈

- (void)createActivityRoll
{
    
    self.activity.frame = CGRectMake(self.flipPage.frame.size.width / 2 - 20 * myWidth, self.flipPage.frame.size.height / 2 - 20 * myHeight, 40 * myWidth, 40 * myHeight);
    self.activity.color = [UIColor grayColor];
    [self.flipPage addSubview:_activity];
    [_activity startAnimating];

}

#pragma mark -  button的点击方法

#pragma mark ** 头条以及热点的照片的点击方法, 点击进入详情

-(void)imageAction:(UIImageView *)myImage
{
    
    HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
    [detail sendMyImage:myImage.image myModel:_detailModel];
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
}
#pragma mark ** 头条, 热点, 稀奇三个button的点击方法

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.bigScroll) {
        if (scrollView.contentOffset.x == self.view.frame.size.width) {
            NSArray *array = self.headerScro.subviews;
            for (UIButton *button in array) {
                if ([button isKindOfClass:[UIButton class]]) {
                   
                    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    button.titleLabel.font = [UIFont systemFontOfSize:17.0f];
                }
                else
                {
                    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                    button.titleLabel.font = [UIFont systemFontOfSize:20.0f];
                }
            }
            [self createTableView];
            
            // 进行网络请求
            firstNum = @0;
            secondNum = @20;
            NSDictionary *dic = [self.buttonArray objectAtIndex:self.bigScroll.contentOffset.x / self.view.frame.size.width];
            [self getConnectionWithURL:dic[@"url"] dicNum:dic[@"dicNum"]];

        }
    }
}

- (void)buttonAction:(id)sender
{
    
    // 切换标题时候，让talbeView滑动到最顶部，并且数组清空
    self.homePageTable.contentOffset = CGPointMake(0, 0);
    [self.talbeViewArray removeAllObjects];
    
    
    // 改变按钮的样式
    NSArray *array = self.headerScro.subviews;
    for (UIView *view in array) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:17.0f];
        }
    }
    
    UIButton *button = (UIButton *)sender;
    NSDictionary *dic = [self.buttonArray objectAtIndex:button.tag - 50];
    self.buttonDic = dic;
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:21.0f];
    
    if ([dic[@"name"] isEqualToString:@"稀奇"]) {
        [self.homePageTable removeFromSuperview];
        if (_xiqiView == nil) {
            [self createLast];
        }
    } else {
        [_xiqiView removeFromSuperview];
        _xiqiView = nil;
        
        // 创建tableView
        [self createTableView];
        
        // 进行网络请求
        firstNum = @0;
        secondNum = @20;
        [self getConnectionWithURL:dic[@"url"] dicNum:dic[@"dicNum"]];
        
    }
}


#pragma mark ** 分享的点击方法

-(void)shareAction:(id)sender
{
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"55dbb3bfe0f55a5d82006783"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren, UMShareToDouban, UMShareToTwitter, UMShareToEmail, nil]
                                       delegate:self];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
   
}

@end
